<?php

class updateAttendanceTask extends sfBaseTask
{
    protected function configure()
    {
        // // add your own arguments here
        $this->addArguments(array(
       new sfCommandArgument('raidid', sfCommandArgument::REQUIRED, 'My argument'),
       new sfCommandArgument('playerid', sfCommandArgument::REQUIRED, 'My argument'),
//       new sfCommandArgument('lastRaidDate', sfCommandArgument::REQUIRED, 'My argument'),
//       new sfCommandArgument('lifetimeRaidAttendanceCount', sfCommandArgument::REQUIRED, 'My argument'),
        ));

        $this->addOptions(array(
                new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, '', 'frontend'),
                new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
                new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'doctrine'),
                // add your own options here
                new sfCommandOption('raidid', null, sfCommandOption::PARAMETER_REQUIRED, 'Raid ID', '-1'),
                new sfCommandOption('playerid', null, sfCommandOption::PARAMETER_REQUIRED, 'Player ID', '-1'),
        ));

        $this->namespace        = 'raidpoints';
        $this->name             = 'updateAttendance';
        $this->briefDescription = '';
        $this->detailedDescription = <<<EOF
The [updatepoints|INFO] task does things.
Call it with:

  [php symfony updatepoints|INFO]
EOF;
    }

    protected function execute($arguments = array(), $options = array())
    {
        // initialize the database connection
        $databaseManager = new sfDatabaseManager($this->configuration);
        $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();

        echo "updateAttendance";
        $raid = $arguments['raidid'];
        $player = $arguments['playerid'];

        $query = Doctrine::getTable("HistoryGuild")
                ->createQuery('h')
                ->select('dt, scheduled_date, raidid')
                ->where('scheduled_date > ?', "0000-00-00")
                ->andWhere('scheduled_date IS NOT NULL')
                ->orderBy('dt');
        $result = $query->setHydrationMode(Doctrine::HYDRATE_SCALAR)->execute();

        $master = array();
        $maxSD = 0;
        foreach ($result as $gh)
        {
            if (!isset($master[$gh['h_raidid']]))
                $master[$gh['h_raidid']] = array();

            if (!isset($master[$gh['h_raidid']][strtotime($gh['h_scheduled_date']." GMT")][$gh['h_dt']]))
                $master[$gh['h_raidid']][strtotime($gh['h_scheduled_date']." GMT")][$gh['h_dt']] = $gh['h_dt'];

            if (strtotime($gh['h_scheduled_date']." GMT") > $maxSD)
                $maxSD = strtotime($gh['h_scheduled_date']." GMT");
        }

        $maxAtt = 0;
        $attDays = explode(",",sfConfig::get("app_attendance_days"));
        foreach ($attDays as $days)
        {
            if ($days > $maxAtt)
                $maxAtt = $days;
        }
        $minSD = $maxSD - ($maxAtt * 60 * 60 * 24);

        $query = Doctrine::getTable("GuildHistory")
                ->createQuery('h')
                ->select('dt, scheduled_date, playerid, raidid')
                ->where('scheduled_date > ?', "0000-00-00")
                ->andWhere('scheduled_date IS NOT NULL')
                ->andWhere('ttype=?', 'P')
                ->andWhere('playerid=?', $player)
                ->orderBy('dt');
        echo $query->getDql();
        $result = $query->setHydrationMode(Doctrine::HYDRATE_SCALAR)->execute();

        $player = array();
        foreach ($result as $gh)
        {
            if (!isset($master[$gh['h_raidid']]))
                $player[$gh['h_raidid']] = array();

            if (!isset($player[$gh['h_raidid']][$gh['h_playerid']]))
                $player[$gh['h_raidid']][$gh['h_playerid']] = array();

            $player[$gh['h_raidid']][$gh['h_playerid']][strtotime($gh['h_scheduled_date']." GMT")][] = $gh['h_dt'];
        }

        $attArray = array();
        $masArray = array();
        $firstAtt = array();
        $masterLifetime = array();
        $playerLifetime = array();

        foreach ($player as $raidid => $raidid_data)
        {
            $firstAtt[$raidid] = array();
            foreach ($raidid_data as $playerid => $playerid_data)
            {
                $firstRaid = 0;
                foreach ($playerid_data as $scheduled_date => $scheduled_date_data)
                {
                    if ($firstRaid == 0 || $firstRaid > $scheduled_date)
                        $firstRaid = $scheduled_date;
                    if ($scheduled_date >= $minSD)
                    {
                        foreach ($attDays as $attDay)
                        {
                            if ($scheduled_date >= ($maxSD - ($attDay * 60 * 60 * 24)))
                            {
                                $attArray[$attDay][$raidid][$playerid][$scheduled_date] = count($scheduled_date_data);
                            }
                        }
                    }
                    $playerLifetime[$raidid][$playerid][$scheduled_date] = count($scheduled_date_data);
                }
                $firstAtt[$raidid][$playerid] = $firstRaid;
            }
        }

        foreach ($master as $raidid => $raidid_data)
        {
            foreach ($raidid_data as $scheduled_date => $scheduled_date_data)
            {
                if ($scheduled_date >= $minSD)
                {
                    foreach ($attDays as $attDay)
                    {
                        if ($scheduled_date >= ($maxSD - ($attDay * 60 * 60 * 24)))
                        {
                            $masArray[$attDay][$raidid][$scheduled_date] = count($scheduled_date_data);
                        }
                    }
                }
                $masterLifetime[$raidid][$scheduled_date] = count($scheduled_date_data);
            }
        }
        //print_r($master);
        //print_r($player);
        //print_r($attArray);

        echo "lifetime:\n";
        foreach ($firstAtt as $raidid => $raidid_data)
        {
            foreach ($raidid_data as $playerid => $firstRaid)
            {
                $pmLifetime = array();
                foreach ($masterLifetime[$raidid] as $scheduled_date => $scheduled_date_data)
                {
                    if ($scheduled_date >= $firstRaid)
                    {
                        $pmLifetime[$scheduled_date] = $scheduled_date_data;
                    }
                }
                echo "playerid: ".$playerid."\t".count($playerLifetime[$raidid][$playerid])."/".count($pmLifetime)."\t".round((count($playerLifetime[$raidid][$playerid])/count($pmLifetime))*100)."\n";
                $query = Doctrine::getTable("PlayerAttendance")
                        ->createQuery('pa')
                        ->select("id")
                        ->where("playerid=?", $playerid)
                        ->andWhere("raidid=?", $raidid)
                        ->andWhere("numdays=?", 0);
                $result = $query->setHydrationMode(Doctrine::HYDRATE_SCALAR)->execute();
                $pa = null;
                if ($result[0]['pa_id'])
                {
                    $query = Doctrine::getTable("PlayerAttendance")
                            ->createQuery('pa')
                            ->update()
                            ->set("percent", round((count($playerLifetime[$raidid][$playerid])/count($pmLifetime))*100))
                            ->where("playerid=?", $playerid)
                            ->andWhere("raidid=?", $raidid)
                            ->andWhere("numdays=?", 0);
                    $query->setHydrationMode(Doctrine::HYDRATE_SCALAR)->execute();
                }
                else
                {
                    $pa = new PlayerAttendance();
                    $pa->setRaidid($playerid);
                    $pa->setPlayerid($raidid);
                    $pa->setNumdays(0);
                    $pa->setPercent(round((count($playerLifetime[$raidid][$playerid])/count($pmLifetime))*100));
                    $pa->save();
                }
            }
        }

        foreach ($attArray as $attDay => $attData)
        {
            echo "attDay: ".$attDay."\n";
            foreach ($attData as $raidid => $raidid_data)
            {
                foreach ($raidid_data as $playerid => $playerid_data)
                {
                    echo "playerid: ".$playerid."\t".count($playerid_data)."/".count($masArray[$attDay][$raidid])."\t".round((count($playerid_data)/count($masArray[$attDay][$raidid]))*100)."\n";

                    $query = Doctrine::getTable("PlayerAttendance")
                            ->createQuery('pa')
                            ->select("id")
                            ->where("playerid=?", $playerid)
                            ->andWhere("raidid=?", $raidid)
                            ->andWhere("numdays=?", $attDay);
                    $result = $query->setHydrationMode(Doctrine::HYDRATE_SCALAR)->execute();
                    $pa = null;
                    if ($result[0]['pa_id'])
                    {
                        $query = Doctrine::getTable("PlayerAttendance")
                                ->createQuery('pa')
                                ->update()
                                ->set("percent", round((count($playerid_data)/count($masArray[$attDay][$raidid]))*100))
                                ->where("playerid=?", $playerid)
                                ->andWhere("raidid=?", $raidid)
                                ->andWhere("numdays=?", $attDay);
                        $query->setHydrationMode(Doctrine::HYDRATE_SCALAR)->execute();
                    }
                    else
                    {
                        $pa = new PlayerAttendance();
                        $pa->setRaidid($playerid);
                        $pa->setPlayerid($raidid);
                        $pa->setNumdays($attDay);
                        $pa->setPercent(round((count($playerid_data)/count($masArray[$attDay][$raidid]))*100));
                        $pa->save();
                    }
                }

            }
        }

        // add your code here
    }
}
